<template>
  <!-- 查找 -->
  <div>
    <el-space>
      <el-input v-model="seekData.title" placeholder="请输入优惠券标题" />
      <el-select class="m-2" placeholder="请选择优惠券类型" v-model="seekData.type">
        <el-option label="满减卷" :value="1" />
        <el-option label="全部" value />
      </el-select>
      <el-select class="m-2" placeholder="请选择优惠券状态" v-model="seekData.status">
        <el-option label="下架" :value="0" />
        <el-option label="正常" :value="1" />
        <el-option label="已过期" :value="-1" />
        <el-option label="全部" value />
      </el-select>
      <el-button type="primary" :icon="Search" @click="findCoupon">查找</el-button>
      <el-button type="primary" :icon="Plus" @click="addCoupon">添加</el-button>
      <el-button type="primary" :icon="Download" @click="exportExcel">当前页导出</el-button>
    </el-space>

    <!-- 优惠券数据表格 -->
    <el-table :data="couponData" border style="width: 100%">
      <el-table-column prop="id" label="优惠券ID" align="center" />
      <el-table-column prop="title" label="优惠券名称" align="center" />
      <el-table-column prop="type" label="优惠券类型" align="center">
        <template #default="scope">{{scope.row.type==1?'满减卷':'全部'}}</template>
      </el-table-column>
      <el-table-column prop="description" label="介绍" align="center" />
      <el-table-column prop="total" label="优惠券数量" align="center" />
      <el-table-column prop="surplus" label="剩余数量" align="center" />
      <el-table-column prop="limit" label="每人限领" align="center" />
      <el-table-column prop="discount" label="满减金额" align="center">
        <template #default="scope">
          <span>减免{{scope.row.discount}}元</span>
        </template>
      </el-table-column>
      <el-table-column prop="min" label="最低消费" align="center">
        <template #default="scope">
          <span>满{{scope.row.min}}元可用</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag>{{condiTion(scope.row)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryTitle" label="使用类目名称" align="center">
        <template #default="scope">
          <el-tag>{{scope.row.categoryTitle?scope.row.categoryTitle:"全部类目"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="使用类目ID" align="center" />
      <el-table-column prop="days" label="领劵相对天数" align="center">
        <template #default="scope">{{scope.row.days?scope.row.days:'无'}}</template>
      </el-table-column>
      <el-table-column prop="gmtStart" label="领劵开始时间" align="center">
        <template
          #default="scope"
        >{{scope.row.gmtStart? new Date(scope.row.gmtStart).followTime():"" }}</template>
      </el-table-column>
      <el-table-column prop="gmtStart" label="领劵结束时间" align="center">
        <template
          #default="scope"
        >{{scope.row.gmtStart? new Date(scope.row.gmtEnd).followTime():"" }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180px">
        <template #default="scope">
          <el-button
            :disabled="scope.row.gmtEnd - Date.parse(new Date()) < 0"
            type="primary"
            @click="changeStatus(scope.row.status ? 0 : 1, scope.row.id)"
          >{{operaTion(scope.row)}}</el-button>
          <el-button type="info" @click="examineCoupon(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="35%" :before-close="handleClose">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        class="demo-ruleForm"
        label-position="right"
        :rules="rules"
        label-width="100px"
        :disabled="title=='编辑'"
      >
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model.trim="ruleForm.title" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select class="m-2" placeholder="请选择优惠券类型" v-model="ruleForm.type">
            <el-option label="满减卷" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input v-model.trim="ruleForm.description" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input v-model.trim="ruleForm.total" placeholder="请输入优惠券数量">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limit">
          <el-input v-model.trim="ruleForm.limit" placeholder="请输入每人限领数量">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount">
          <el-input v-model.trim="ruleForm.discount" placeholder="请输入优惠金额">
            <template #append>{{ruleForm.discount}}元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input v-model.trim="ruleForm.min" placeholder="请输入最低消费">
            <template #append>{{ruleForm.min}}元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-select class="m-2" placeholder="请选择优惠券状态" v-model="ruleForm.status">
            <el-option label="下架" :value="0" />
            <el-option label="正常" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-row style="margin-bottom:10px">
            <el-radio-group v-model="getCoupon">
              <el-radio-button label="领劵相对天数" />
              <el-radio-button label="指定绝对时间" />
            </el-radio-group>
          </el-row>
          <el-input
            v-model="ruleForm.days"
            v-if="getCoupon=='领劵相对天数'"
            oninput="value=value.replace(/[^\d]/g,'')"
          >
            <template #append>天</template>
          </el-input>
          <el-row v-if="getCoupon=='指定绝对时间'">
            <el-col :span="11">
              <el-date-picker
                v-model="ruleForm.gmtStart"
                type="date"
                placeholder="选择日期"
                value-format="x"
              />
            </el-col>
            <el-col class="text-center" :span="1" style="margin: 0 0.6rem">至</el-col>
            <el-col :span="11">
              <el-date-picker
                v-model="ruleForm.gmtEnd"
                type="date"
                placeholder="选择日期"
                value-format="x"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="category">
            <el-radio-button label="全场通用" />
            <el-radio-button label="指定分类" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类目" v-if="category=='指定分类'">
          <el-cascader :options="options" :props="props" v-model="ruleForm.categoryId" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd('ruleFormRef')" v-if="title=='创建'">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <pa-ging v-bind="pages" @changePage="changePage" @changeLimit="changeLimit" />
  </div>
</template>
<script>
import { Search, Plus, Download } from "@element-plus/icons-vue";
import FileSaver from "file-saver";
import { utils, write } from "xlsx";
import { post } from "@/utlis/http";
export default {
  setup() {
    return {
      Search,
      Plus,
      Download,
    };
  },
  data() {
    return {
      seekData: {
        title: "",
        type: "",
        status: "",
      },
      pages: {
        page: 1, //页
        limit: 10, //条
        total: 10, //总条数
      },
      couponData: [], //优惠券数据
      dialogVisible: false, //对话框
      title: "创建", //判断是添加还是编辑的对话框
      ruleForm: {
        title: "", //优惠券名称
        type: "", //优惠券类型
        description: "", //介绍
        total: 1, //优惠券数量
        limit: 1, //每人限领
        discount: 1, //优惠金额
        min: 1, //最低消费
        status: "", //优惠券状态
        days: "", //有效期
        categoryTitle: "", //优惠类目
        gmtStart: "", //开始时间
        gmtEnd: "", //结束时间
        categoryId: "", //优惠类别
      },
      getCoupon: "领劵相对天数",
      category: "全场通用",
      options: [],
      props: {
        checkStrictly: true, //是否严格的遵守父子节点不互相关联
        value: "id", //指定选项的值为选项对象的某个属性值
        label: "title", //指定选项标签为选项对象的某个属性值
        children: "childrenList", //指定选项的子选项为选项对象的某个属性值
        emitPath: false, //在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
      },
      rules: {
        // 添加表单验证
        title: [
          { required: true, message: "请您输入优惠券名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请您选择优惠券类型", trigger: "change" },
        ],
        total: [
          { required: true, message: "请您输入优惠券数量", trigger: "blur" },
          {
            pattern: /^([1-9]\d*|[1]{1,1})$/,
            message: "请您输入整数",
            trigger: "blur",
          },
        ],
        limit: [
          { required: true, message: "请您输入优惠券限领数", trigger: "blur" },
          {
            pattern: /^([1-9]\d*|[1]{1,1})$/,
            message: "请您输入整数",
            trigger: "blur",
          },
        ],
        discount: [
          { required: true, message: "请您输入优惠金额", trigger: "blur" },
          {
            pattern: /^([1-9]\d*|[1]{1,1})$/,
            message: "请您输入整数",
            trigger: "blur",
          },
        ],
        min: [
          { required: true, message: "请您输入优最低消费", trigger: "blur" },
          {
            pattern: /^([1-9]\d*|[1]{1,1})$/,
            message: "请您输入整数",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: "请您选择优惠券类型", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.initiaLize();
  },
  methods: {
    // 渲染数据
    initiaLize() {
      let data = {
        _gp: "admin.coupon",
        _mt: "list",
        title: this.seekData.title,
        type: this.seekData.type,
        status: this.seekData.status,
        pageNo: this.pages.page,
        limit: this.pages.limit,
      };
      post(data).then((res) => {
        let { data, errno } = res.data;
        if (200 == errno) {
          this.couponData = data.items;
          this.pages.total = data.total;
        }
      });
    },
    // 添加
    addCoupon() {
      this.title = "创建";
      this.category = "全场通用";
      this.getCoupon = "领劵相对天数";
      this.categoryTree();
      this.dialogVisible = true;
      Object.keys(this.ruleForm).forEach((key) => {
        //key值全部清空
        this.ruleForm[key] = "";
      });
    },
    //确认添加
    confirmAdd(ruleFormRef) {
      this.$refs[ruleFormRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          let data = {
            _gp: "admin.coupon",
            _mt: "create",
            ...this.ruleForm,
          };
          if (this.ruleForm.gmtEnd < this.ruleForm.gmtStart) {
            ElMessage.warning("结束时间不得小于开始时间");
            return;
          }
          if (this.ruleForm.limit > 2) {
            ElMessage.warning("每人限领数量只能1或2张");
            return;
          }
          post(data).then((res) => {
            let { errno, errmsg } = res.data;
            if (200 == errno) {
              ElMessage.success("添加成功");
              this.dialogVisible = false;
              this.initiaLize();
            } else {
              ElMessage.warning(errmsg);
            }
          });
        }
      });
    },
    //编辑
    examineCoupon(row) {
      Object.assign(this.ruleForm, row);
      this.title = "编辑";
      this.categoryTree();
      this.dialogVisible = true;
      if (row.categoryId) {
        this.category = "指定分类";
      }
      if (!row.days) {
        this.getCoupon = "指定绝对时间";
      } else {
        this.getCoupon = "领劵相对天数";
        this.category = "全场通用";
      }
    },
    //渲染添加数据中的指定分类数据
    categoryTree() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      post(data).then((res) => {
        let { errno, data } = res.data;
        if (200 == errno) {
          this.options = data;
        }
      });
    },
    //操作
    operaTion(row) {
      if (row.gmtEnd - Date.parse(new Date()) < 0) {
        return "过期";
      } else if (row.status == 1) {
        return "下架";
      } else {
        return "正常";
      }
    },
    //状态
    condiTion(row) {
      if (row.gmtEnd - Date.parse(new Date()) < 0) {
        return "已过期";
      } else if (row.status == 1) {
        return "正常";
      } else {
        return "下架";
      }
    },
    // 正常或下架
    changeStatus(status, rowId) {
      let data = {
        _gp: "admin.coupon",
        _mt: "updateCouponStatus",
        id: rowId,
        status: status,
      };
      post(data).then((res) => {
        let { errno, errmsg } = res.data;
        if (200 == errno) {
          ElMessage({
            type: "success",
            message: status ? "下架成功" : "修改正常成功",
          });
          this.initiaLize();
        } else {
          ElMessage.warning(errmsg);
        }
      });
    },
    // 当前页导出
    exportExcel() {
      var wb = utils.table_to_book(document.querySelector(".el-table"));
      var wbout = write(wb, { bookType: "xlsx", bookSST: true, type: "array" });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "优惠券管理.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //查找
    findCoupon() {
      this.initiaLize();
    },
    //条
    changeLimit(val) {
      this.pages.limit = val;
      this.initiaLize();
    },
    //页
    changePage(val) {
      this.pages.page = val;
      this.initiaLize();
    },
    // 对话框
    handleClose() {
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0 40px 0;
}
.from {
  margin: auto;
  & /deep/ .el-form-item__label::before {
    content: "*";
    color: red;
    margin-right: 5px;
  }
}
</style>